package test;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ChatService {

    @Value("${ai.config.deepseek.apiKey}")
    private String apiKey;

    @Value("${ai.config.deepseek.baseUrl}")
    private String apiUrl;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public void streamChat(String question, SseEmitter emitter) throws Exception {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost request = createHttpRequest(question);
            
            try (CloseableHttpResponse response = client.execute(request);
                 BufferedReader reader = new BufferedReader(
                         new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {
                
                processStreamResponse(reader, emitter);
            }
        }
    }

    private HttpPost createHttpRequest(String question) throws Exception {
        HttpPost request = new HttpPost(apiUrl);
        request.setHeader("Content-Type", "application/json");
        request.setHeader("Authorization", "Bearer " + apiKey);

        Map<String, Object> message = new HashMap<>();
        message.put("role", "user");
        message.put("content", question);

        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("model", "deepseek-r1:7b");
        requestMap.put("messages", Collections.singletonList(message));
        requestMap.put("stream", true);

        String requestBody = objectMapper.writeValueAsString(requestMap);
        request.setEntity(new StringEntity(requestBody, StandardCharsets.UTF_8));
        
        return request;
    }

    private void processStreamResponse(BufferedReader reader, SseEmitter emitter) throws Exception {
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("data: ")) {
                String jsonData = line.substring(6);
                if ("[DONE]".equals(jsonData)) {
                    break;
                }
                
                JsonNode node = objectMapper.readTree(jsonData);
                String content = node.path("choices")
                        .path(0)
                        .path("delta")
                        .path("content")
                        .asText("");
                        
                if (!content.isEmpty()) {
                    emitter.send(content);
                }
            }
        }
    }
}
